import * as WebSocket from 'ws';
import {IO} from "./io";
import {makeId} from "./idMaker";
import {contextManager} from "./manager";

export class Context {
  id: number;
  ws: WebSocket;
  user: { name: string, uid: number };
  room: Room;

  emit(type: string, data: any) {
    const msg = {
      data,
      $router: type
    };
    this.ws.send(JSON.stringify(msg));
  }

  broadcast(type, data, filter?: WebSocket) {
    this.room.broadcast(type, data, filter)
  }

}

export class Room {
  connections: Array<Context> = [];
  id: number;
  maxCount: number;
  isStart: boolean = false;

  broadcast(type, data, filter?: WebSocket) {
    this.connections.filter(value => value.ws != filter).forEach(value => value.emit(type, data));
  }

  broadcastPos(data: any) {
    Object.keys(data).forEach(key => {
      const copy = Object.assign({}, data);
      const id = parseInt(key);
      const ctx = contextManager.getCtxById(id);
      delete copy[key];
      this.broadcast('pos', copy)
    })
  }
}

